<?php



class FicheVitrineDefaultModuleFrontController extends VitrineFrontController {
	
	public function initContent() 
	{
		// LVM
		//@session_start();

		// Pb : $_SESSION pas définie...
		//var_dump($_SESSION);
		parent :: initContent();
		
		//var_dump($_SESSION);
		
		$this->loginAsCustomer();
		$customer = Context::getContext()->customer;
		
		$link = new Link();
		
		$linkModule = $link->getModuleLink('fichevitrine', 'default');
		$linkAddFiche = $link->getModuleLink('fichevitrine', 'addfiche');
		$linkAddModel = $link->getModuleLink('fichevitrine', 'addmodel');
		$linkListModel = $link->getModuleLink('fichevitrine', 'list', array("type"=>Fiche::FICHE_MODELE));
		$linkListFiche = $link->getModuleLink('fichevitrine', 'list', array("type" => Fiche::FICHE));
		$linkPrint = $link->getModuleLink('fichevitrine', 'print');
		
		// LVM
		// Pas possible de l'appeler car fonction protected donc accessible seulement dans la classe AuthControllerCore 
		// dans controllers/front/AuthController.php
		//$controller = new AuthControllerCore();
		
		if (Tools::isSubmit('SubmitLogin'))
		{
			//$controller->processSubmitLogin();
			$this->processSubmitLogin();
		}
		
		$connected = $this->isConnected();
		
		$date_end = '';
		$weight = 0;
		$abo = null;
		
		if ($connected == true)
			$abo = FicheAbo::getFicheAbo($customer->id);	
			
		if ($abo != null)
		{
			// LVM
			//$weight = $abo->storeSize / Fiche::WEIGHT_MODULATOR;
			$maxWeight = $abo->storeSize / Fiche::WEIGHT_MODULATOR;
			
			$time = strtotime($abo->date_end);
			$date_end = date(Context::getContext()->language->date_format_lite, $time);
			//setlocale(LC_TIME, );
			
			// LVM
			$weightModulator = Fiche::WEIGHT_MODULATOR;
			$totalWeight = round(Fiche::getTotalWeight($customer) / $weightModulator , 2);
			$percentWeight = round((float)( ($totalWeight / $maxWeight) * 100 ),2);
			$numModels = Fiche::getTotalFicheWhere(array('type' => Fiche::FICHE_MODELE, 'id_customer' => $customer->id));
			$numFiches = Fiche::getTotalFicheWhere(array('type' => Fiche::FICHE, 'id_customer' => $customer->id));
		}
		else
		{
			// LVM : pour éviter warning variable undefined
			$maxWeight = '';	
			$totalWeight = '';
			$percentWeight = '';
			$numModels = ''; 
			$numFiches = '';
		}
		
		// LVM
		if (!is_array($this->errors))
			$errors = array();
		else
			$errors = $this->errors;
			
		$this->context->smarty->assign(array(
			'moduleName' => 'fichevitrine',
			'connected' => $connected,
			'abo' => $abo,
			
			// LVM
			//'weight' => $weight,
			'maxWeight' => $maxWeight,
			
			// LVM
			'numModels' 		=> $numModels,
			'numFiches' 		=> $numFiches,
			'totalWeight'		=> $totalWeight,
			'percentWeight'		=> $percentWeight,
			
			'manual' => Fiche::getManURI(),
			'date_end' => $date_end,
			'customer' => $customer,
			'linkModule' => $linkModule,
			'linkHome' => $linkModule,
			'linkPrint' => $linkPrint,
			'linkAddFiche' => $linkAddFiche,
			'linkAddModel' => $linkAddModel,
			'linkListFiche' => $linkListFiche,
			'linkListModel' => $linkListModel,
			'path' => 'Fiche Vitrine'
		));
		
		// LVM : pour éviter erreur lors de la déconnexion
		$this->context->smarty->assign('authentification_error', $this->errors);
		
		// LVM : lien vers la page standard de login avec la création d'un compte (en plus)
		$linkLoginStd = 'index.php?controller='.(($this->authRedirection !== false) ? url_encode($this->authRedirection) : 'my-account');
		
		$this->context->smarty->assign('linkLoginStd', $linkLoginStd);
		
		
		$this->setTemplate('fichevitrine.tpl');	
	}
	
	// LVM : copie fonction dans controllers/front/AuthController.php
	/**
	 * Process login
	 */
	protected function processSubmitLogin()
	{
		Hook::exec('actionBeforeAuthentication');
		
		$passwd = trim(Tools::getValue('passwd'));
		$email = trim(Tools::getValue('email'));
		
		if (empty($email))
		{
			$this->errors[] = Tools::displayError('An email address required.');
		}
		elseif (!Validate::isEmail($email))
		{
			$this->errors[] = Tools::displayError('Invalid email address.');
		}
		elseif (empty($passwd))
		{
			$this->errors[] = Tools::displayError('Password is required.');
		}
		elseif (!Validate::isPasswd($passwd))
		{
			$this->errors[] = Tools::displayError('Invalid password.');
		}
		else
		{
			$customer = new Customer();
			
			$authentication = $customer->getByEmail(trim($email), trim($passwd));
			
			if (!$authentication || !$customer->id)
			{
				$this->errors[] = Tools::displayError('Authentication failed.');
			}
			else
			{
				$this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare: CompareProduct::getIdCompareByIdCustomer($customer->id);
				$this->context->cookie->id_customer = (int)($customer->id);
				$this->context->cookie->customer_lastname = $customer->lastname;
				$this->context->cookie->customer_firstname = $customer->firstname;
				$this->context->cookie->logged = 1;
				$customer->logged = 1;
				$this->context->cookie->is_guest = $customer->isGuest();
				$this->context->cookie->passwd = $customer->passwd;
				$this->context->cookie->email = $customer->email;
				
				// Add customer to the context
				$this->context->customer = $customer;
				
				if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && $id_cart = (int)Cart::lastNoneOrderedCart($this->context->customer->id))
					$this->context->cart = new Cart($id_cart);
				else
				{
					$this->context->cart->id_carrier = 0;
					$this->context->cart->setDeliveryOption(null);
					$this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int)($customer->id));
					$this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int)($customer->id));
				}
				$this->context->cart->id_customer = (int)$customer->id;
				$this->context->cart->secure_key = $customer->secure_key;
				$this->context->cart->save();
				$this->context->cookie->id_cart = (int)$this->context->cart->id;
				$this->context->cookie->write();
				$this->context->cart->autosetProductAddress();

				Hook::exec('actionAuthentication');

				// Login information have changed, so we check if the cart rules still apply
				CartRule::autoRemoveFromCart($this->context);
				CartRule::autoAddToCart($this->context);

				if (!$this->ajax)
				{
					if ($back = Tools::getValue('back'))
						Tools::redirect(html_entity_decode($back));
						
					// LVM : ne pas rediriger vers la page standard	Prestashop mais la page d'accueil de LFV
					//Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? url_encode($this->authRedirection) : 'my-account'));
					$link = new Link();
					$linkModuleHome = $link->getModuleLink('fichevitrine', 'default');
					
					Tools::redirect($linkModuleHome);			
				}
			}
		}
		
		if ($this->ajax)
		{
			$return = array(
				'hasError' => !empty($this->errors),
				'errors' => $this->errors,
				'token' => Tools::getToken(false)
			);
			
			die(Tools::jsonEncode($return));
		}
		else
			$this->context->smarty->assign('authentification_error', $this->errors);
	}
	
}
